#!/bin/bash

# 定义颜色
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
CYAN="\033[36m"
MAGENTA="\033[35m"
RESET="\033[0m"

# 常用时区列表（使用字符串存储，兼容 sh）
COMMON_TIMEZONES="UTC Asia/Shanghai Asia/Tokyo Asia/Kolkata America/New_York Europe/London"

# 临时文件存储搜索结果
SEARCH_RESULTS_FILE="/tmp/timezone_search_results.txt"

# 检测当前时区
check_current_timezone() {
    current_timezone=$(timedatectl | grep "Time zone" | awk '{print $3}')
    current_time=$(timedatectl | grep "Local time" | awk '{print $3,$4,$5}')
    printf "${GREEN}当前时区: ${current_timezone}${RESET}\n"
    printf "${GREEN}当前时间: ${current_time}${RESET}\n"
}

# 显示主菜单
show_menu() {
    printf "\n${BLUE}========== 时区设置工具 ==========${RESET}\n"
    printf "${BLUE}请选择操作:${RESET}\n"
    i=1
    for timezone in $COMMON_TIMEZONES; do
        printf "${GREEN}${i}) ${timezone}${RESET}\n"
        i=$((i + 1))
    done
    printf "${MAGENTA}${i}) 手动输入时区名称${RESET}\n"
    printf "${CYAN}$((i + 1))) 高级搜索时区${RESET}\n"
    printf "${CYAN}$((i + 2))) 查看所有可用时区${RESET}\n"
    printf "${CYAN}$((i + 3))) 时区详情查询${RESET}\n"
    printf "${CYAN}$((i + 4))) 时区使用说明${RESET}\n"
    printf "${YELLOW}$((i + 5))) 退出${RESET}\n"
    printf "${BLUE}=================================${RESET}\n"
    read -p "输入选项 (1-$((i + 5))): " choice
}

# 分页显示内容
paginate_content() {
    local content="$1"
    local page_size=20
    local total_lines=$(echo "$content" | wc -l)
    local current_page=1
    local total_pages=$(( (total_lines + page_size - 1) / page_size ))
    
    while true; do
        clear
        printf "${CYAN}========== 查看结果 (第 ${current_page}/${total_pages} 页) ==========${RESET}\n"
        echo "$content" | sed -n "$((( current_page - 1 ) * page_size + 1)),$((current_page * page_size))p" | cat -n
        printf "\n${BLUE}总共 ${total_lines} 条结果${RESET}\n"
        printf "${YELLOW}操作: [n]下一页 [p]上一页 [q]返回 [s]选择序号${RESET}\n"
        read -p "请选择操作: " action
        
        case "$action" in
            n|N)
                if [ $current_page -lt $total_pages ]; then
                    current_page=$((current_page + 1))
                else
                    printf "${RED}已经是最后一页${RESET}\n"
                    sleep 1
                fi
                ;;
            p|P)
                if [ $current_page -gt 1 ]; then
                    current_page=$((current_page - 1))
                else
                    printf "${RED}已经是第一页${RESET}\n"
                    sleep 1
                fi
                ;;
            s|S)
                read -p "请输入要选择的序号: " line_num
                if [ "$line_num" -ge 1 ] && [ "$line_num" -le "$total_lines" ]; then
                    selected_timezone=$(echo "$content" | sed -n "${line_num}p")
                    printf "${YELLOW}您选择了: ${selected_timezone}${RESET}\n"
                    read -p "确认设置此时区吗? (y/n): " confirm
                    if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
                        validate_and_set_timezone "$selected_timezone"
                        return
                    fi
                else
                    printf "${RED}无效的序号${RESET}\n"
                    sleep 1
                fi
                ;;
            q|Q)
                return
                ;;
            *)
                printf "${RED}无效操作${RESET}\n"
                sleep 1
                ;;
        esac
    done
}

# 高级搜索时区
advanced_search_timezones() {
    printf "\n${CYAN}========== 高级时区搜索 ==========${RESET}\n"
    printf "${GREEN}支持的搜索方式:${RESET}\n"
    printf "1. 按地区: Asia, Europe, America, Africa, Australia, Pacific\n"
    printf "2. 按国家: China, Japan, USA, UK, Germany, France\n"
    printf "3. 按城市: Shanghai, Tokyo, London, New_York, Paris\n"
    printf "4. 组合搜索: 多个关键词用空格分隔，如: Asia Shanghai\n"
    printf "5. 排除搜索: 使用 -关键词 排除，如: Asia -Hong_Kong\n\n"
    
    read -p "请输入搜索关键词 (直接回车查看所有): " keywords
    
    if [ -z "$keywords" ]; then
        # 显示所有时区
        printf "${CYAN}正在获取所有时区...${RESET}\n"
        timedatectl list-timezones > "$SEARCH_RESULTS_FILE"
    else
        # 处理搜索关键词
        all_timezones=$(timedatectl list-timezones)
        result="$all_timezones"
        
        for keyword in $keywords; do
            if echo "$keyword" | grep -q "^-"; then
                # 排除关键词
                exclude_word=$(echo "$keyword" | sed 's/^-//')
                result=$(echo "$result" | grep -v -i "$exclude_word")
            else
                # 包含关键词
                result=$(echo "$result" | grep -i "$keyword")
            fi
        done
        
        echo "$result" > "$SEARCH_RESULTS_FILE"
    fi
    
    result_count=$(wc -l < "$SEARCH_RESULTS_FILE")
    if [ "$result_count" -eq 0 ]; then
        printf "${RED}未找到匹配的时区${RESET}\n"
        read -p "按 Enter 键返回主菜单..." dummy
        return
    fi
    
    printf "${GREEN}找到 ${result_count} 个匹配的时区${RESET}\n"
    content=$(cat "$SEARCH_RESULTS_FILE")
    paginate_content "$content"
}

# 显示所有可用时区（优化版）
show_all_timezones() {
    printf "${CYAN}正在获取所有可用时区...${RESET}\n"
    all_timezones=$(timedatectl list-timezones)
    total_count=$(echo "$all_timezones" | wc -l)
    printf "${GREEN}系统共有 ${total_count} 个可用时区${RESET}\n"
    paginate_content "$all_timezones"
}

# 时区详情查询
timezone_details() {
    printf "\n${CYAN}========== 时区详情查询 ==========${RESET}\n"
    read -p "请输入要查询的时区名称: " query_timezone
    
    if [ -z "$query_timezone" ]; then
        printf "${RED}请输入有效的时区名称${RESET}\n"
        read -p "按 Enter 键返回主菜单..." dummy
        return
    fi
    
    # 验证时区是否存在
    if timedatectl list-timezones | grep -q "^${query_timezone}$"; then
        printf "\n${GREEN}========== ${query_timezone} 详细信息 ==========${RESET}\n"
        
        # 临时设置时区查看时间（不实际修改系统时区）
        current_tz=$(timedatectl | grep "Time zone" | awk '{print $3}')
        
        printf "${YELLOW}时区名称:${RESET} ${query_timezone}\n"
        
        # 显示该时区的当前时间
        TZ="$query_timezone" date
        printf "${YELLOW}当前时间:${RESET} $(TZ="$query_timezone" date)\n"
        
        # 显示与当前时区的时差
        current_timestamp=$(date +%s)
        target_timestamp=$(TZ="$query_timezone" date +%s)
        time_diff=$(( (target_timestamp - current_timestamp) / 3600 ))
        
        if [ $time_diff -eq 0 ]; then
            printf "${YELLOW}时差:${RESET} 与当前时区相同\n"
        elif [ $time_diff -gt 0 ]; then
            printf "${YELLOW}时差:${RESET} 比当前时区快 ${time_diff} 小时\n"
        else
            printf "${YELLOW}时差:${RESET} 比当前时区慢 $((-time_diff)) 小时\n"
        fi
        
        # 显示地理位置信息
        region=$(echo "$query_timezone" | cut -d'/' -f1)
        city=$(echo "$query_timezone" | cut -d'/' -f2)
        printf "${YELLOW}地区:${RESET} ${region}\n"
        printf "${YELLOW}城市:${RESET} ${city}\n"
        
        printf "\n${CYAN}是否要设置为此时区?${RESET}\n"
        read -p "确认设置 (y/n): " confirm
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            validate_and_set_timezone "$query_timezone"
        fi
    else
        printf "${RED}时区 '${query_timezone}' 不存在${RESET}\n"
        
        # 智能建议相似时区
        printf "\n${YELLOW}搜索相似时区...${RESET}\n"
        similar=$(timedatectl list-timezones | grep -i "$query_timezone" | head -5)
        if [ -n "$similar" ]; then
            printf "${CYAN}找到相似的时区:${RESET}\n"
            echo "$similar" | cat -n
        else
            printf "${RED}未找到相似的时区${RESET}\n"
        fi
    fi
    
    read -p "按 Enter 键返回主菜单..." dummy
}

# 显示时区使用说明（增强版）
show_timezone_help() {
    printf "\n${CYAN}========== 时区使用说明 ==========${RESET}\n"
    printf "${GREEN}时区格式说明:${RESET}\n"
    printf "• 标准格式: 地区/城市 (如 Asia/Shanghai)\n"
    printf "• UTC 格式: UTC+8, UTC-5 等\n"
    printf "• 特殊时区: GMT, UTC, CET, EST 等\n\n"
    
    printf "${GREEN}常见时区对照:${RESET}\n"
    printf "• 中国标准时间: Asia/Shanghai (UTC+8)\n"
    printf "• 日本标准时间: Asia/Tokyo (UTC+9)\n"
    printf "• 韩国标准时间: Asia/Seoul (UTC+9)\n"
    printf "• 印度标准时间: Asia/Kolkata (UTC+5:30)\n"
    printf "• 美国东部时间: America/New_York (UTC-5/-4)\n"
    printf "• 美国西部时间: America/Los_Angeles (UTC-8/-7)\n"
    printf "• 英国时间: Europe/London (UTC+0/+1)\n"
    printf "• 德国时间: Europe/Berlin (UTC+1/+2)\n\n"
    
    printf "${GREEN}实用命令:${RESET}\n"
    printf "• 查看当前时区: ${BLUE}timedatectl${RESET}\n"
    printf "• 查看所有时区: ${BLUE}timedatectl list-timezones${RESET}\n"
    printf "• 搜索时区: ${BLUE}timedatectl list-timezones | grep 关键词${RESET}\n"
    printf "• 查看指定时区时间: ${BLUE}TZ='Asia/Tokyo' date${RESET}\n"
    printf "• 临时使用时区: ${BLUE}TZ='Europe/London' 命令${RESET}\n\n"
    
    printf "${YELLOW}注意事项:${RESET}\n"
    printf "• 修改时区需要 root 或 sudo 权限\n"
    printf "• 时区名称严格区分大小写\n"
    printf "• 某些时区有夏令时，会自动调整\n"
    printf "• 建议使用完整路径，避免使用缩写\n"
    printf "• 修改时区后可能需要重启某些服务\n"
    
    printf "${CYAN}=================================${RESET}\n"
    read -p "按 Enter 键返回主菜单..." dummy
}

# 根据选项获取时区
get_timezone_by_choice() {
    local choice_num=$1
    local count=1
    for timezone in $COMMON_TIMEZONES; do
        if [ "$count" -eq "$choice_num" ]; then
            echo "$timezone"
            return 0
        fi
        count=$((count + 1))
    done
    return 1
}

# 验证并设置时区（增强版）
validate_and_set_timezone() {
    local timezone="$1"
    
    # 验证时区是否存在
    if timedatectl list-timezones | grep -q "^${timezone}$"; then
        # 显示即将设置的时区信息
        printf "\n${CYAN}========== 时区设置确认 ==========${RESET}\n"
        printf "${YELLOW}目标时区:${RESET} ${timezone}\n"
        printf "${YELLOW}目标时间:${RESET} $(TZ="$timezone" date)\n"
        
        read -p "确认设置此时区吗? (y/n): " final_confirm
        if [ "$final_confirm" = "y" ] || [ "$final_confirm" = "Y" ]; then
            printf "${BLUE}正在设置时区为 ${timezone}...${RESET}\n"
            timedatectl set-timezone "$timezone"
            if [ $? -eq 0 ]; then
                printf "${GREEN}✓ 时区已成功修改为: ${timezone}${RESET}\n"
                printf "\n${CYAN}========== 当前时间信息 ==========${RESET}\n"
                timedatectl | head -4
                
                printf "\n${BLUE}========== 实用命令参考 ==========${RESET}\n"
                printf "${GREEN}时区管理命令:${RESET}\n"
                printf "• 查看当前时区详情: ${YELLOW}timedatectl${RESET}\n"
                printf "• 查看当前时区状态: ${YELLOW}timedatectl status${RESET}\n"
                printf "• 列出所有可用时区: ${YELLOW}timedatectl list-timezones${RESET}\n"
                printf "• 搜索特定时区: ${YELLOW}timedatectl list-timezones | grep 关键词${RESET}\n"
                
                printf "\n${GREEN}时间查看命令:${RESET}\n"
                printf "• 查看当前时间: ${YELLOW}date${RESET}\n"
                printf "• 查看UTC时间: ${YELLOW}date -u${RESET}\n"
                printf "• 查看指定时区时间: ${YELLOW}TZ='时区名' date${RESET}\n"
                printf "• 格式化时间显示: ${YELLOW}date '+%%Y-%%m-%%d %%H:%%M:%%S'${RESET}\n"
                
                printf "\n${GREEN}系统时间同步:${RESET}\n"
                printf "• 启用网络时间同步: ${YELLOW}timedatectl set-ntp true${RESET}\n"
                printf "• 手动同步时间: ${YELLOW}ntpdate pool.ntp.org${RESET}\n"
                printf "• 查看NTP同步状态: ${YELLOW}timedatectl show-timesync${RESET}\n"
                
                printf "\n${GREEN}应用程序相关:${RESET}\n"
                printf "• 重启相关服务: ${YELLOW}systemctl restart rsyslog crond${RESET}\n"
                printf "• 更新系统时区文件: ${YELLOW}dpkg-reconfigure tzdata${RESET} (Debian/Ubuntu)\n"
                printf "• 临时使用时区运行命令: ${YELLOW}TZ='${timezone}' 你的命令${RESET}\n"
                
                printf "\n${CYAN}========================================${RESET}\n"
                printf "${GREEN}时区设置完成！感谢使用本工具！${RESET}\n"
                printf "${YELLOW}提示: 某些应用可能需要重启才能生效${RESET}\n"
                exit 0
            else
                printf "${RED}✗ 时区修改失败，请检查权限！${RESET}\n"
                printf "${YELLOW}提示: 可能需要 sudo 权限${RESET}\n"
            fi
        else
            printf "${YELLOW}取消设置时区${RESET}\n"
        fi
    else
        printf "${RED}✗ 时区 '${timezone}' 不存在${RESET}\n"
        printf "${YELLOW}建议:${RESET}\n"
        printf "1. 检查拼写是否正确 (区分大小写)\n"
        printf "2. 使用高级搜索功能查找时区\n"
        printf "3. 查看时区详情确认名称\n\n"
        
        # 智能建议功能增强
        city_name=$(echo "$timezone" | sed 's/.*\///')
        region_name=$(echo "$timezone" | sed 's/\/.*//')
        
        printf "${CYAN}智能建议:${RESET}\n"
        similar_by_city=$(timedatectl list-timezones | grep -i "$city_name" | head -3)
        similar_by_region=$(timedatectl list-timezones | grep -i "$region_name" | head -3)
        
        if [ -n "$similar_by_city" ]; then
            printf "${GREEN}按城市名搜索:${RESET}\n"
            echo "$similar_by_city"
        fi
        
        if [ -n "$similar_by_region" ] && [ "$similar_by_region" != "$similar_by_city" ]; then
            printf "${GREEN}按地区名搜索:${RESET}\n"
            echo "$similar_by_region"
        fi
    fi
}

# 手动输入时区（增强版）
manual_input_timezone() {
    printf "\n${CYAN}========== 手动输入时区 ==========${RESET}\n"
    printf "${GREEN}格式示例:${RESET}\n"
    printf "• Asia/Shanghai (中国)\n"
    printf "• Europe/London (英国)\n"
    printf "• America/New_York (美国东部)\n"
    printf "• Australia/Sydney (澳大利亚)\n\n"
    
    printf "${YELLOW}小贴士:${RESET}\n"
    printf "• 可以使用高级搜索功能查找所需时区\n"
    printf "• 可以使用时区详情功能验证时区\n"
    printf "• 输入 '?' 查看搜索建议\n\n"
    
    read -p "请输入时区名称: " custom_timezone
    
    if [ "$custom_timezone" = "?" ]; then
        printf "${CYAN}进入高级搜索模式...${RESET}\n"
        sleep 1
        advanced_search_timezones
        return
    fi
    
    if [ -n "$custom_timezone" ]; then
        validate_and_set_timezone "$custom_timezone"
    else
        printf "${RED}时区名称不能为空${RESET}\n"
    fi
}

# 获取时区列表长度
get_timezone_count() {
    count=0
    for timezone in $COMMON_TIMEZONES; do
        count=$((count + 1))
    done
    echo $count
}

# 清理临时文件
cleanup() {
    rm -f "$SEARCH_RESULTS_FILE"
}

# 脚本退出时清理
trap cleanup EXIT

# 主逻辑
printf "${GREEN}欢迎使用时区设置工具！${RESET}\n"
printf "${CYAN}提示: 此工具需要适当权限来修改系统时区${RESET}\n"

while true; do
    check_current_timezone
    show_menu
    timezone_count=$(get_timezone_count)
    
    if [ "$choice" -ge 1 ] && [ "$choice" -le "$timezone_count" ]; then
        selected_timezone=$(get_timezone_by_choice "$choice")
        validate_and_set_timezone "$selected_timezone"
    elif [ "$choice" -eq $((timezone_count + 1)) ]; then
        manual_input_timezone
    elif [ "$choice" -eq $((timezone_count + 2)) ]; then
        advanced_search_timezones
    elif [ "$choice" -eq $((timezone_count + 3)) ]; then
        show_all_timezones
    elif [ "$choice" -eq $((timezone_count + 4)) ]; then
        timezone_details
    elif [ "$choice" -eq $((timezone_count + 5)) ]; then
        show_timezone_help
    elif [ "$choice" -eq $((timezone_count + 6)) ]; then
        printf "${YELLOW}感谢使用时区设置工具！${RESET}\n"
        break
    else
        printf "${RED}无效选项，请重新输入！${RESET}\n"
    fi
    
    # 添加分隔线
    printf "\n${MAGENTA}================================${RESET}\n"
done